package com.kuizii.base.common.utils;

import lombok.extern.slf4j.Slf4j;

import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * @Author: nuanyang
 * @Date: 2019/8/22 0022 15:27
 */
@Slf4j
public class MACUtil {
    public static String getIp() {
        String ip;
        try {
            List<String> ipList = getHostAddress(null);
            // default the first
            ip = (!ipList.isEmpty()) ? ipList.get(0) : "";
        } catch (Exception ex) {
            ip = "";
            log.warn("Utils get IP warn", ex);
        }
        return ip;
    }

    public static String getIp(String interfaceName) {
        String ip;
        interfaceName = interfaceName.trim();
        try {
            List<String> ipList = getHostAddress(interfaceName);
            ip = (!ipList.isEmpty()) ? ipList.get(0) : "";
        } catch (Exception ex) {
            ip = "";
            log.warn("Utils get IP warn", ex);
        }
        return ip;
    }

    /**
     * 获取已激活网卡的IP地址
     *
     * @param interfaceName 可指定网卡名称,null则获取全部
     * @return List<String>
     */
    public static List<String> getHostAddress(String interfaceName) {
        List<String> ipList = new ArrayList<String>(5);
        try {

            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();
                if (networkInterface.isLoopback()) {
                    continue;
                }
                 Enumeration<InetAddress> allAddress = networkInterface.getInetAddresses();
                while (allAddress.hasMoreElements()) {
                    InetAddress address = allAddress.nextElement();
                    if (address.isLoopbackAddress()) {
                        // skip the loopback addr
                        continue;
                    }
                    if (address instanceof Inet6Address) {
                        // skip the IPv6 addr
                        continue;
                    }
                    String hostAddress = address.getHostAddress();
                    if (null == interfaceName) {
                        ipList.add(hostAddress);
                    } else if (interfaceName.equals(networkInterface.getDisplayName())) {
                        ipList.add(hostAddress);
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
            log.error("获取本机IP出错"+ e);
        }

        return ipList;
    }
}

